package com.pansoft.openplanet.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.efounder.chat.activity.BaseActivity;
import com.efounder.chat.utils.CommonThreadPoolUtils;
import com.efounder.chat.view.CommonOtherPopWindow;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.util.EnvSupportManager;
import com.efounder.utils.ResStringUtil;
import com.pansoft.nfc.ChangeCardPasswordActivity;
import com.pansoft.nfc.mifare.Common;
import com.pansoft.nfc.mifare.activity.MifareResetCardPwActivity;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.adapter.AssetCardsDetailsListAdapter;
import com.pansoft.openplanet.bean.CardBean;
import com.pansoft.openplanet.bean.CardWalletInfo;
import com.pansoft.openplanet.db.AccountDao;
import com.pansoft.openplanet.db.CardDao;
import com.pansoft.openplanet.util.BalanceUtil;
import com.pansoft.openplanet.util.TCAccountManager;
import com.pansoft.openplanet.util.TCRequestUtil;
import com.pansoft.openplanet.widget.PassWordAlertDialog;
import com.pansoft.openplanet.widget.WrapContentLinearLayoutManager;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.utilcode.util.ToastUtils;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;

import static com.pansoft.openplanet.activity.WalletTypeSelectActivity.MODE_CREATE_NEW;

/**
 * 卡包详情界面
 *
 * @author maming
 * @date 2019/4/18 20:28
 */
public class NewAssetCardsDetailsActivity extends BaseActivity implements View.OnClickListener {
    //
    private TextView tv_title;
    private ImageView iv_add;
    private RecyclerView recyclerView;
    private SmartRefreshLayout refreshLayout;
    //
    private CardBean cardBean;
    private String uid;
    private List<CardWalletInfo> cardWalletInfoList;
    private AssetCardsDetailsListAdapter cardsDetailsListAdapter;
    private int count = 0;//计数
    /**
     * 是否显示卡号
     */
    private boolean isShowNum = Boolean.parseBoolean(EnvironmentVariable.getProperty("cards_show_num", "true"));

    public static void start(Context context, String uid) {
        Intent starter = new Intent(context, NewAssetCardsDetailsActivity.class);
        starter.putExtra("uid", uid);
        context.startActivity(starter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.open_planet_activity_asset_card_details);
        initView();
        initData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (cardWalletInfoList == null) {
            return;
        }
        cardWalletInfoList.clear();
        cardWalletInfoList.addAll(new CardDao(this).getCardBean(uid).getWalletInfoList());
        cardBean.setWalletInfoList(cardWalletInfoList);
        cardsDetailsListAdapter.notifyDataSetChanged();
    }

    /**
     * 初始化控件
     */
    private void initView() {
        tv_title = (TextView) findViewById(R.id.tv_title);
        iv_add = (ImageView) findViewById(R.id.iv_add);
        iv_add.setOnClickListener(this);
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        refreshLayout = (SmartRefreshLayout) findViewById(R.id.refreshLayout);
        iv_add.setVisibility(View.VISIBLE);
    }

    /**
     * 初始化数据
     */
    private void initData() {
        uid = getIntent().getStringExtra("uid");
        //设置界面的标题
        CommonThreadPoolUtils.execute(new Runnable() {
            @Override
            public void run() {
                cardBean = new CardDao(NewAssetCardsDetailsActivity.this).getCardBean(uid);
                cardBean.setShowNum(isShowNum);
                //设置里面钱包的眼睛状态
                List<CardWalletInfo> walletInfos = cardBean.getWalletInfoList();
                if (walletInfos != null) {
                    for (CardWalletInfo walletInfo : walletInfos) {
                        walletInfo.setShowNum(isShowNum);
                    }
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tv_title.setText(CardBean.getCardTypeName(cardBean.getCardType()));
                        //设置适配器
                        recyclerView.setLayoutManager(new WrapContentLinearLayoutManager(NewAssetCardsDetailsActivity.this));
                        cardsDetailsListAdapter = new AssetCardsDetailsListAdapter(NewAssetCardsDetailsActivity.this, cardBean);
                        recyclerView.setAdapter(cardsDetailsListAdapter);
                        cardWalletInfoList = cardBean.getWalletInfoList();
                        //请求余额
                        if (cardWalletInfoList == null) {
                            return;
                        }
                        for (CardWalletInfo c :
                                cardWalletInfoList) {
                            requestWalletBalance(c);
                        }
                        initListener();
                    }
                });
            }
        });

    }

    /**
     * 请求钱包余额数据
     */
    private void requestWalletBalance(final CardWalletInfo cardWalletInfo) {
        HashMap<String, String> params = new HashMap<>();
        //链编号：BTC传1，ETH传2
        params.put("chainID", String.valueOf(cardWalletInfo.getChainId()));
        //用户钱包地址
        params.put("userAddress", cardWalletInfo.getAddress());
        TCRequestUtil.getCommonRequest(TAG, "chain/getAllTokenBalanceByChainAndUserAddress",
                params, new TCRequestUtil.TCRequestCallback() {
                    @Override
                    public void onSuccess(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            //
                            if (jsonObject.optString("result").equals("success")) {
                                //
                                String balance = jsonObject.optString("AddressBalance", "0");
                                //
                                if ("0".equals(balance) || "".equals(balance)) {
                                    cardWalletInfo.setWalletBalance("0");
                                } else {
                                    balance = BalanceUtil.formatPrice(Double.valueOf(balance), true, 8);
                                    cardWalletInfo.setWalletBalance(balance);
                                }
                                cardsDetailsListAdapter.notifyDataSetChanged();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            refreshLayout.finishRefresh();
                            ToastUtils.showShort(ResStringUtil.getString(R.string.common_text_http_request_data_fail));
                        }
                        refreshLayout.finishRefresh();
                    }

                    @Override
                    public void onFail(String error) {
                        refreshLayout.finishRefresh();
                        ToastUtils.showShort(ResStringUtil.getString(R.string.common_text_http_request_data_fail));
                    }
                });
    }

    /**
     * 初始化点击事件
     */
    private void initListener() {
        //下拉刷新的点击事件
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                //请求余额
                if (cardWalletInfoList == null) {
                    return;
                }
                for (CardWalletInfo c :
                        cardWalletInfoList) {
                    requestWalletBalance(c);
                }
            }
        });
        //眼睛按钮的点击事件
        cardsDetailsListAdapter.setOnEyeShowNumClickListener(new AssetCardsDetailsListAdapter.OnEyeShowNumClickListener() {
            @Override
            public void isShowNmu() {
                isShowNum = !isShowNum;
                saveShowNumStatus(isShowNum);
                cardBean.setShowNum(isShowNum);
                for (CardWalletInfo cardWalletInfo : cardWalletInfoList) {
                    cardWalletInfo.setShowNum(isShowNum);
                }
                cardsDetailsListAdapter.notifyDataSetChanged();
            }
        });
    }

    /**
     * 保存是否显示数据信息的状态
     */
    private void saveShowNumStatus(boolean isShowNum) {
        EnvironmentVariable.setProperty("cards_show_num", String.valueOf(isShowNum));
    }

    /**
     * 删除卡片，判断卡片有无钱包
     * 如果有，提醒不能删除
     * 如果没有，从数据库中删除该卡片
     */
    private void deleteCard() {
        new AlertDialog.Builder(this)
                .setTitle(R.string.common_text_hint)
                .setMessage(ResStringUtil.getString(R.string.star_asset_whether_remove_card))
                .setPositiveButton(R.string.common_text_confirm, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        deleteFromServer();
                    }
                })
                .setNegativeButton(R.string.common_text_cancel, null).show();
    }

    /**
     * 修改卡片PIN密码
     */
    private void changeCardPw() {
        ChangeCardPasswordActivity.start(this, cardBean.getUid());
    }

    private void resetCardPw() {
        PassWordAlertDialog passWordAlertDialog = new PassWordAlertDialog(this, new PassWordAlertDialog.OnEnterClick() {
            @Override
            public void passVerifySuccess(String passWord) {
                Intent intent;
                if (!EnvSupportManager.isSupportNfcWallet() && !EnvSupportManager.isSupportForceBleNfc()) {
                    return;
                }
                if (!EnvSupportManager.isSupportForceBleNfc() && Common.hasMifareClassicSupport(NewAssetCardsDetailsActivity.this)){
                    intent = new Intent(NewAssetCardsDetailsActivity.this, MifareResetCardPwActivity.class);
                } else {
                    intent = new Intent(NewAssetCardsDetailsActivity.this, BleBlutoothScanActivity.class);
                    intent.putExtra("createType", BleBlutoothScanActivity.TYPE_RESET_PIN);
                    intent.putExtra("bleDeviceType", BleBlutoothScanActivity.BLE_TYPE_NFC);
                }
                intent.putExtra("cardNo", uid);
                startActivity(intent);
            }
        });
        passWordAlertDialog.show();
    }


    /**
     * 将卡片删除，同时将资产的钱包从数据库删除
     */
    private void deleteFromServer() {
        showLoading(R.string.common_text_please_wait);
        CommonThreadPoolUtils.execute(new Runnable() {
            @Override
            public void run() {
                AccountDao accountDao = new AccountDao(NewAssetCardsDetailsActivity.this);
                int totalCount = cardBean.getWalletInfoList().size();
                if (new TCAccountManager(NewAssetCardsDetailsActivity.this).removeCard(
                        EnvironmentVariable.getProperty("tc_ethAddress"), uid)) {
                    //移除卡片成功
                    //删除本地数据库
                    for (int i = 0; i < cardBean.getWalletInfoList().size(); i++) {
                        CardWalletInfo cardWalletInfo = cardBean.getWalletInfoList().get(i);
                        new AccountDao(NewAssetCardsDetailsActivity.this).delete(cardWalletInfo.getAddress());
                    }
                    new CardDao(NewAssetCardsDetailsActivity.this).delete(cardBean.getUid());
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            dismissLoading();
                            ToastUtils.showShort(R.string.star_asset_card_remove_success);
                            finish();
                        }
                    });
                } else {
                    dismissLoading();
                    //删除失败，不处理
                    ToastUtils.showShort(R.string.star_asset_card_remove_fail);
                }
            }
        });
    }

    /**
     * 点击事件
     */
    @Override
    public void onClick(View view) {
        showPopWindow();
    }

    /**
     * 添加钱包的菜单
     */
    private void showPopWindow() {
        final CommonOtherPopWindow commonOtherPopWindow = new CommonOtherPopWindow(NewAssetCardsDetailsActivity.this);
        commonOtherPopWindow.addMenuButton(ResStringUtil.getString(R.string.wechatview_add_wallet), 0)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        WalletTypeSelectActivity.start(NewAssetCardsDetailsActivity.this,
                                MODE_CREATE_NEW, true);
                        commonOtherPopWindow.dismiss();
                    }
                });
        commonOtherPopWindow.addMenuButton(ResStringUtil.getString(R.string.star_asset_card_change_password), 0)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        changeCardPw();
                        commonOtherPopWindow.dismiss();
                    }
                });
        commonOtherPopWindow.addMenuButton(ResStringUtil.getString(R.string.star_asset_card_reset_PIN), 0)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        resetCardPw();
                        commonOtherPopWindow.dismiss();
                    }
                });
        commonOtherPopWindow.addMenuButton(ResStringUtil.getString(R.string.open_planet_delete_card), 0)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        deleteCard();
                        commonOtherPopWindow.dismiss();
                    }
                });
        commonOtherPopWindow.showPopupWindow(iv_add);
    }
}
